from rest_framework import serializers

from user import userser
from .models import Post, Comment, PostLike, PostStar



#帖子序列化器
class PostSerializer(serializers.ModelSerializer):
    user = userser.UserSerializer(read_only=True)
    image = serializers.ImageField(required=False, allow_null=True)
    class Meta:
        model = Post
        fields = "__all__"


# 帖子列表序列化器（用于API响应）
class PostListSerializer(serializers.ModelSerializer):
    user = userser.UserSerializer(read_only=True)
    like_count = serializers.IntegerField(read_only=True)
    star_count = serializers.IntegerField(read_only=True)
    comment_count = serializers.IntegerField(read_only=True)
    created_at = serializers.DateTimeField(format='%Y-%m-%dT%H:%M:%SZ')
    
    class Meta:
        model = Post
        fields = ['id', 'title', 'content', 'user', 'like_count', 'star_count', 
                 'comment_count', 'created_at', 'image', 'category', 'source', 'tags']


class CommentSerializer(serializers.ModelSerializer):
    user = userser.UserSerializer(read_only=True)
    replies = serializers.SerializerMethodField()
    created_at = serializers.DateTimeField(format='%Y-%m-%dT%H:%M:%SZ')
    class Meta:
        model = Comment
        fields = ['id', 'post', 'user', 'content', 'created_at', 'parent', 'replies']
    def get_replies(self, obj):
        # 序列化二级回复
        if obj.replies.exists():
            return CommentSerializer(obj.replies.all(), many=True).data
        return []


# 点赞操作序列化器
class LikeActionSerializer(serializers.Serializer):
    action = serializers.ChoiceField(choices=['like', 'unlike'])
    user_id = serializers.IntegerField()


# 收藏操作序列化器
class StarActionSerializer(serializers.Serializer):
    action = serializers.ChoiceField(choices=['star', 'unstar'])
    user_id = serializers.IntegerField()


# 评论创建序列化器
class CommentCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ['post', 'content', 'parent']


# 用户操作状态序列化器
class UserActionStatusSerializer(serializers.Serializer):
    liked_posts = serializers.DictField(child=serializers.BooleanField())
    starred_posts = serializers.DictField(child=serializers.BooleanField())


# 用户操作同步序列化器
class UserActionSyncSerializer(serializers.Serializer):
    user_id = serializers.IntegerField()
    actions = UserActionStatusSerializer()